import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../app_views.dart';

class RegisterView extends GetView<AuthLogic> {
  const RegisterView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('注册星命账号')),
      body: LayoutBuilder(
        builder: (_, constraints) {
          final isWide = constraints.maxWidth > 600;
          return Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFFDF6EC), Color(0xFFF1F6FF)],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            child: SafeArea(
              child: Center(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(20),
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxWidth: isWide ? 520 : 380),
                    child: Obx(() {
                      final state = controller.state.value;
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '创建你的命盘档案',
                            style: Theme.of(context)
                                .textTheme
                                .displayLarge
                                ?.copyWith(fontSize: 28),
                          ),
                          const SizedBox(height: 10),
                          const Text('绑定手机号或邮箱，即可开始奇妙的命理旅途'),
                          const SizedBox(height: 24),
                          SegmentedButton<bool>(
                            segments: const <ButtonSegment<bool>>[
                              ButtonSegment<bool>(
                                value: true,
                                label: Text('手机号注册'),
                                icon: Icon(Icons.phone_iphone),
                              ),
                              ButtonSegment<bool>(
                                value: false,
                                label: Text('邮箱注册'),
                                icon: Icon(Icons.alternate_email),
                              ),
                            ],
                            selected: <bool>{state.isSmsLogin},
                            onSelectionChanged: (value) {
                              controller.toggleLoginMode(value.first);
                            },
                          ),
                          const SizedBox(height: 24),
                          Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: isWide ? 32 : 20,
                              vertical: isWide ? 32 : 24,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(24),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.08),
                                  blurRadius: 20,
                                  offset: const Offset(0, 12),
                                ),
                              ],
                            ),
                            child: Column(
                              children: [
                                if (state.isSmsLogin)
                                  _buildPhoneRegister(state)
                                else
                                  _buildEmailRegister(state),
                                CheckboxListTile(
                                  value: state.agreeTerms,
                                  onChanged: (value) => controller
                                      .onAgreeTermsChanged(value ?? false),
                                  title: const Text('我已阅读并同意《星命之境用户协议》'),
                                  controlAffinity:
                                      ListTileControlAffinity.leading,
                                ),
                                if (state.errorMessage != null) ...[
                                  const SizedBox(height: 12),
                                  Text(
                                    state.errorMessage!,
                                    style: const TextStyle(
                                        color: Colors.redAccent),
                                  ),
                                ],
                                const SizedBox(height: 24),
                                SizedBox(
                                  width: double.infinity,
                                  child: ElevatedButton(
                                    onPressed: state.isLoading
                                        ? null
                                        : controller.register,
                                    child: state.isLoading
                                        ? const SizedBox(
                                            height: 18,
                                            width: 18,
                                            child: CircularProgressIndicator(
                                                strokeWidth: 2),
                                          )
                                        : const Text('立即注册'),
                                  ),
                                ),
                                const SizedBox(height: 12),
                                TextButton(
                                  onPressed: () {
                                    controller.clearAllInputs(); // 清空输入
                                    Get.back();
                                  },
                                  child: const Text('返回登录'),
                                ),
                              ],
                            ),
                          ),
                        ],
                      );
                    }),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildPhoneRegister(AuthState state) {
    return Column(
      children: [
        TextField(
          controller: TextEditingController(text: state.phone)
            ..selection = TextSelection.collapsed(offset: state.phone.length),
          keyboardType: TextInputType.phone,
          onChanged: controller.onPhoneChanged,
          decoration: InputDecoration(
            labelText: '手机号',
            prefixIcon: const Icon(Icons.phone_android),
            errorText: state.phoneError,
          ),
        ),
        const SizedBox(height: 18),
        TextField(
          controller: TextEditingController(text: state.phoneSmsCode)
            ..selection =
                TextSelection.collapsed(offset: state.phoneSmsCode.length),
          keyboardType: TextInputType.number,
          onChanged: controller.onPhoneSmsCodeChanged,
          decoration: InputDecoration(
            labelText: '短信验证码',
            prefixIcon: const Icon(Icons.sms),
            errorText: state.phoneSmsError,
            suffixIcon: TextButton(
              onPressed: state.phoneSmsCountdown > 0
                  ? null
                  : (state.phoneError == null && state.phone.isNotEmpty)
                      ? controller.requestSmsCode
                      : null,
              child: Text(
                state.phoneSmsCountdown > 0
                    ? '${state.phoneSmsCountdown}s'
                    : '获取验证码',
              ),
            ),
          ),
        ),
        const SizedBox(height: 18),
        TextField(
          controller: TextEditingController(text: state.phonePassword)
            ..selection =
                TextSelection.collapsed(offset: state.phonePassword.length),
          obscureText: true,
          onChanged:
              controller.onPhonePasswordChanged, // 注意这里是 onPhonePasswordChanged
          decoration: InputDecoration(
            labelText: '设置密码',
            prefixIcon: const Icon(Icons.lock),
            errorText: state.phonePasswordError, // 注意这里是 phonePasswordError
          ),
        ),
      ],
    );
  }

  Widget _buildEmailRegister(AuthState state) {
    return Column(
      children: [
        TextField(
          controller: TextEditingController(text: state.email)
            ..selection = TextSelection.collapsed(offset: state.email.length),
          keyboardType: TextInputType.emailAddress,
          onChanged: controller.onEmailChanged,
          decoration: InputDecoration(
            labelText: '邮箱地址',
            prefixIcon: const Icon(Icons.email_outlined),
            errorText: state.emailError,
          ),
        ),
        const SizedBox(height: 18),
        TextField(
          controller: TextEditingController(text: state.emailCode)
            ..selection =
                TextSelection.collapsed(offset: state.emailCode.length),
          keyboardType: TextInputType.number,
          onChanged: controller.onEmailCodeChanged,
          decoration: InputDecoration(
            labelText: '邮箱验证码',
            prefixIcon: const Icon(Icons.verified),
            errorText: state.emailCodeError, // 注意这里是 emailCodeError
            suffixIcon: TextButton(
              onPressed: state.emailCountdown > 0
                  ? null
                  : (state.emailError == null && state.email.isNotEmpty)
                      ? controller.requestEmailCode
                      : null,
              child: Text(
                state.emailCountdown > 0 ? '${state.emailCountdown}s' : '获取验证码',
              ),
            ),
          ),
        ),
        const SizedBox(height: 18),
        TextField(
          controller: TextEditingController(text: state.emailPassword)
            ..selection =
                TextSelection.collapsed(offset: state.emailPassword.length),
          obscureText: true,
          onChanged:
              controller.onEmailPasswordChanged, // 注意这里是 onEmailPasswordChanged
          decoration: InputDecoration(
            labelText: '设置密码',
            prefixIcon: const Icon(Icons.lock_outline),
            errorText: state.emailPasswordError, // 注意这里是 emailPasswordError
          ),
        ),
      ],
    );
  }
}
